package main

import (
	"fmt"
	"sync"
)

var jobStateChM sync.Map

func main() {
	mapIfNoTest()
	//mapTest()
}

func mapIfNoTest() {
	//obj := make(map[string]interface{})
	cMap := make(map[string]interface{})
	cMap["北京"] = "北京"
	cMap["安徽省"] = "合肥"
	cMap["江西"] = "南昌"
	MapIfNo(&cMap, "江苏", "南京")
	MapIfNo(&cMap, "江苏", "苏州")
	MapIfNo(&cMap, "江苏", "无锡")
	fmt.Println("执行MapIfNo完成：字典：", cMap)
	
	//使用ok-idiom:有时候需要准确地判断map中是否存在特定的键,可以使用ok-idiom
	value, isfind := cMap["江西"]
	if isfind {
		fmt.Println("字典ok-idiom：", value)
	} else {
		fmt.Println("字典 not find the key 值: ", isfind)
	}
	
	for key, value := range cMap {
		fmt.Printf("键%s——值->%s \n", key, value)
	}
}

func MapIfNo(m *map[string]interface{}, key string, value interface{}) {
	if m != nil {
		if _, ok := (*m)[key]; !ok {
			(*m)[key] = value
		}
	}
}

func mapTest() {
	BindJobState("id111")
	BindJobState("id222")
	BindJobState("id333")
	PutJobState("id333")
	fmt.Println("执行！完成：jobStateChM", jobStateChM)
	
	if value, isFind := jobStateChM.Load("id222"); isFind {
		fmt.Println("sync.MapLoad加载的值是：", value)
	}
}

func BindJobState(key string) chan string {
	psch := make(chan string)
	jobStateChM.Store(key, psch)
	return psch
}

func PutJobState(id string) {
	jobStateChM.Range(func(key, value interface{}) bool {
		if ch, ok := value.(chan string); ok {
			go func() {
				ch <- id
			}()
		}
		return true
	})
}
